<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>方向键控制div改进</title>
	</head>
	<body>
		<div id="box1"></div>
	</body>
</html>
<script type="text/javascript">
	var box1 = document.getElementById("box1")
	var speed = 20;
	// 创建一个变量表示方向
	 var dir = 0;
	// 为防止按住一个键不放时会有卡顿，开启一个定时器控制div移动
	setInterval(function(){
		if(dir == 38){
			box1.style.top = (box1.offsetTop - speed) + "px"
		}
		else if(dir == 40){
			box1.style.top = (box1.offsetTop + speed) + "px"
		}
		else if(dir == 37){
			box1.style.left = (box1.offsetLeft - speed) + "px"
		}
		else if(dir == 39){
			box1.style.left = (box1.offsetLeft + speed) + "px"
		}
	},30)
	document.onkeydown = function(e){
		dir = e.keyCode;
		if(e.shiftKey)
			speed = 50;
	}
	document.onkeyup = function(e){
		dir = 0;
		speed = 20;
	}
</script>

<style type="text/css">
	#box1{
		width: 6.25rem;
		height: 6.25rem;
		background-color: red;
		position: absolute;
	}
</style>
